export function animationUpdate(callback) {
    callbackList.push(callback);
    if (!isRunning) {
        lastTime = new Date().getTime();
        requestAnimationFrame(loop);
        isRunning = true;
    }
}

export function removeAnimationUpdate(callback) {
    if (isLooping) {
        removeList.push(callback);
    } else {
        callbackList = callbackList.filter(e => e !== callback);
    }
}

let isRunning = false;
let lastTime = 0;
let isLooping = false;

function loop(time) {
    if (!isRunning) {
        return;
    }
    isLooping = true;

    if (callbackList.length <= 0) {
        isRunning = false;
        isLooping = false;
        return;
    }

    if (removeList.length > 0) {
        for (let i = 0; i < removeList.length; i++) {
            callbackList = callbackList.filter(e => e !== removeList[i]);
        }
        removeList = [];
    }

    const curTime = new Date().getTime();
    const dt = curTime - lastTime;
    lastTime = curTime;

    for (let i = 0; i < callbackList.length; i++) {
        callbackList[i](dt);
    }

    isLooping = false;
    requestAnimationFrame(loop);
}

let callbackList = [];
let removeList = [];